<?php

namespace App\Service\OpenShop\Feishu;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Models\Common\FileTranscodingJobModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderLogModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel as ResourceModel;
use App\Service\Common\UploadTranscoding;
use App\Support\ChangeSupport;
use Illuminate\Support\Facades\DB;

class UploadFileResourceService
{

    public static function insertData($data)
    {
        try {
            ResourceModel::query()
                         ->insert($data);
        } catch (\Exception $exception) {
            throw new ResponseHttpException(BaseErrorCode::$UPLOAD_FILE_ERR);
        }
    }

    /**
     * 根据订单号和位置列表查询文件
     * @param string $orderNo 订单号
     * @param array $positionList 模块位置枚举列表 如 UploadFileResourceEnum::USER_POSITION_LIST
     */
    public static function getFileListByPosition($orderNo, $positionList)
    {
        return ResourceModel::query()
                            ->where('orderNo', $orderNo)
                            ->where('isDeleted', 0)
                            ->whereIn('position', $positionList)
                            ->orderBy('id', 'desc')
                            ->get();
    }

    /**
     * 修改文件附件
     * @param string $orderNo 订单编号
     * @param array $positionList 位置枚举列表
     * @param array $newFileList 新的文件列表
     */
    public static function updateFileListByPosition($orderNo, $positionList, $newFileList, $changeTheme)
    {
        try {
            ChangeSupport::getInstance()->attachBatchUpdate(
                new ResourceModel(),
                function ($query) use ($orderNo, $positionList) {
                    $query->where("orderNo", $orderNo)
                          ->whereIn("position", $positionList)
                          ->where("isDeleted", 0);
                },
                (array)$newFileList,
                $changeTheme,
                ResourceModel::$orderLogTranslate
            );
        } catch (\Exception $exception) {
            throw new ResponseHttpException(BaseErrorCode::$SET_FILE_ERR);
        }
    }

    /**
     * 返回处理过的文件列表
     * @param $orderNo
     * @param $position
     * @return array|null
     */
    public static function getFileList($orderNo, $position)
    {
        $fileList = UploadFileResourceService::getFileListByPosition($orderNo, $position);
        if (empty($fileList->toArray())) {
            return null;
        } else {
            return UploadFileResourceEnum::handleFileRes($fileList,
                UploadFileResourceEnum::SPACE_DESIGN_DATABASE_LIST);
        }
    }

    public static function setFileListByPositionNoLog($orderNo, $position, $newFileList)
    {
        try {
            DB::beginTransaction();
            //软删除旧的数据
            ResourceModel::query()
                         ->where('orderNo', $orderNo)
                         ->where('position', $position)
                         ->delete();
            //新增新的
            //如果是视频则进行转码
            if (
                in_array(
                    $position,
                    [
                        UploadFileResourceEnum::SHOP_ADDRESS_SHOP_VIDEO,
                        UploadFileResourceEnum::FLOOR_EXPLANATION_VIDEO,
                        UploadFileResourceEnum::PERIPHERAL_VIDEO,
                        UploadFileResourceEnum::SHOP_IN_VIDEO,
                    ])
            ) {
                foreach ($newFileList as $file) {
                    $uploadFileResourceModel = new ResourceModel();
                    foreach ($file as $key => $item) {
                        $uploadFileResourceModel->$key = $item;
                    }
                    $uploadFileResourceModel->save();

                    // 判断视频是否已经转码
                    if (strpos($file['url'], '_encoded.mp4') !== false) {
                        continue;
                    }

                    //添加转码任务
                    $jobId                                 = UploadTranscoding::asyncFileTranscoding($file['url'],
                        config('file-transcoding.kf-file'));
                    $fileTranscodingModel                  = new FileTranscodingJobModel();
                    $fileTranscodingModel->jobId           = $jobId;
                    $fileTranscodingModel->model           = get_class($uploadFileResourceModel);
                    $fileTranscodingModel->filePath        = $file['url'];
                    $fileTranscodingModel->updatedField    = 'url';
                    $fileTranscodingModel->updatedModelId  = $uploadFileResourceModel->id;
                    $fileTranscodingModel->filePathEncoded = substr($file['url'], 0,
                            strrpos($file['url'], '.')) . '_encoded.mp4';
                    $fileTranscodingModel->status          = FileTranscodingJobModel::STATUS_WAIT;
                    $fileTranscodingModel->save();
                }
            } else {
                ResourceModel::query()->insert($newFileList);
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ResponseHttpException(BaseErrorCode::$SET_FILE_ERR);
        }
    }

    public static function setFileListByPositionList($orderNo, $positionList, $newFileList, $businessId)
    {
        try {
            DB::beginTransaction();
            //软删除旧的数据
            ResourceModel::query()
                         ->where('orderNo', $orderNo)
                         ->whereIn('position', $positionList)
                         ->where('businessId', $businessId)
                         ->delete();
            //新增新的
            ResourceModel::query()->insert($newFileList);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ResponseHttpException(BaseErrorCode::$SET_FILE_ERR);
        }
    }

}
